<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018-06-29
 * Time: 10:34
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\Order as OrderModel;
use app\lib\enum\OrderStatusEnum;
use app\lib\exception\OrderException;
use app\api\model\Comments as CommentsModel;
use app\lib\exception\SuccessMessage;
use think\Db;
use think\Exception;
use app\api\service\Token as TokenService;

class Comments extends BaseController
{
    // 保存用户对订单的评论信息
    public function saveComments(){
        $commentsArray = input('post.');
        $order_no = $commentsArray['order_no'];
        $order = OrderModel::where('order_no', '=', $order_no)->find();
        if(!$order){
            throw new OrderException();
        }
        Db::startTrans();
        try{
        $success = CommentsModel::saveComment($order->id, $commentsArray['comments']);
            if($success){
                $comments = new CommentsModel();
                $result = $comments->updateOrderStatus($order->id);
                if($result){
                    Db::commit();
                    return json(new SuccessMessage([
                        'code' => 200,
                        'msg' => '评论数据保存成功'
                    ]),200);
                }else{
                    throw new OrderException([
                        'msg' => '订单状态更新异常',
                        'errorCode' => 80005,
                        'code' => 403
                    ]);
                }
            }else{
                throw new OrderException([
                    'msg' => '订单评论异常，请稍后评价',
                    'errorCode' => 80004,
                    'code' => 403
                ]);
            }
        }catch (Exception $exception){
            Db::rollback();
            throw $exception;
        }
    }

}